#include "temperaturethread.h"
#include "wiringPiSPI.h"
#include "wiringPi.h"
#include <QDebug>

TemperatureThread::TemperatureThread(QThread *parent) :
    QThread(parent)
{
    this->start();
}

void TemperatureThread::run()
{
    int spi1;
    int spiChannel = 0;
    int clock = 1000000;
    wiringPiSetup();
    spi1 = wiringPiSPISetup(spiChannel,clock);

    unsigned char buf[2] = {0, 0};
    memset(buf,0,sizeof(buf));
    while (1) {
        m_mutex.lock();
        if(spi1!=-1)
        {
            wiringPiSPIDataRW(0, buf, 2);
            int ad = buf[0]<< 8 | buf[1];
            int ad_value = (ad >>3)&0xFFF;
            float temperature = ad_value*1023.75/4095;
            if(temperature>=100)
            {
                temperature=100;
            }
            emit sendTemp(temperature);
        }
        delay(10000);
        m_mutex.unlock();
    }
}

void TemperatureThread::readTemperature()
{
    int spi1;
    int spiChannel = 0;
    int clock = 1000000;
    wiringPiSetup();
    spi1 = wiringPiSPISetup(spiChannel,clock);
    if(spi1!=-1)
    {
        unsigned char buf[2] = {0, 0};
        memset(buf,0,sizeof(buf));
        wiringPiSPIDataRW(0, buf, 2);
        //        printf("Manufacturer ID = %x\n", buf[0]);
        //        printf("DevId_1 = %x\n", buf[1]);

        int ad = buf[0]<< 8 | buf[1];
        int ad_value = (ad >>3)&0xFFF;
        float temperature = ad_value*1023.75/4095;
        //        qDebug()<< "==== ad    : " << ad_value;
        //        qDebug()<< "====real temop: " << temperature;
        emit sendTemp(temperature);
    }
}
